<template>
  <el-card>
    <div slot="header">
      <h3>{{ pageTitle }}</h3>
    </div>
    <div>
      <el-row type="flex" justify="end" v-if="!pageState.view">
        <el-button
          v-if="showBtn('高级关联')"
          type="text"
          size="large"
          icon="el-icon-link"
          @click="handleSeniorAssociated"
        >高级关联</el-button
        >
        <el-button
          v-if="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleAssociatedGoods"
          >关联商品</el-button
        >
        <el-button
          v-if="tableData.length > 0"
          type="text"
          size="large"
          @click="handleExportData"
          :loading="loading.export"
          :disabled="tableData.length === 0"
          >模板导出</el-button
        >
        <a
          ><Upload
            :show-upload-list="false"
            :format="['xlsx', 'xls', 'csv']"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :on-format-error="handleUploadFormatError"
            :before-upload="handleBeforeUpload"
            :action="`${uploadBaseURL}sysback/update/product/package/savePackageToPage`"
            ><el-button type="text" size="large">模板导入</el-button></Upload
          ></a
        >
        <template v-if="canOpeState">
          <el-button
            type="text"
            size="large"
            @click="handleSaveData"
            :loading="loading.submit"
            :disabled="tableData.length === 0"
            >暂存</el-button
          >
          <el-button
            type="text"
            size="large"
            @click="handleSubmit"
            :loading="loading.submit"
            :disabled="tableData.length === 0"
            >提交</el-button
          >
        </template>
        <el-button
          v-if="!pageState.menu"
          type="text"
          size="large"
          @click="handleGoBack"
          >返回</el-button
        >
      </el-row>
      <!-- 发起原因输入框 -->
      <LaunchReasonInput
        :reason.sync="launchReason"
        :isDisabled="pageState.view"
      />
      <el-row class="format_table_wrap">
        <general-table
          :loading="loading.table"
          :data-source="tableData"
          :columns="tableColumns"
          height='500'
          @handleCancelSelect="handleCancelSelect"
          @handleChangeInputNumber="handleChangeInputNumber"
        />
      </el-row>
      <!-- 表尾字段 -->
      <FooterFields :footerFields="footerFields" />
    </div>
    <!-- 关联商品-SKU维度弹框 -->
    <AssociatedGoodsModal
      ref="link"
      :columns="associatedGoods.columns"
      :requestApi="associatedGoods.requestApi"
      :requestParams="associatedGoods.requestParams"
      :distinctParams="associatedGoods.distinctParams"
      @submitAction="handleGetTableData"
    />
    <!-- 选择计量单位弹框组件 -->
    <SelectUnitDialog
      :visible.sync="mainUnitVisible"
      @getUnitName="handleReturnMainUnitName"
    />
    <!-- 选择产地弹框 -->
    <OriginalPlaceDialog
      :visible.sync="originalPlaceVisible"
      @getOriginalPlace="getOriginalPlaceFn"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorAssociated.visible"
      :columns="seniorAssociated.columns"
      :dataSource="seniorAssociated.dataSource"
      :submitLimitLength="5000"
      @seniorSearchResult="getSeniorResultFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
/* components */
import GeneralTable from '@/pages/commodity/modules/components/generalTable';
import FooterFields from '@/pages/commodity/components/FooterFields';
import AssociatedGoodsModal from '@/components/common/dialog/associatedGoods/associatedGoodsDialog';
import SelectUnitDialog from '@/pages/commodity/components/SelectUnitDialog';
import OriginalPlaceDialog from '@/components/common/dialog/originalPlaceDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import LaunchReasonInput from '@/components/LaunchReasonInput';
/* mixins */
import skuDimensionMixins from '@/components/common/dialog/associatedGoods/mixins/skuDimension';
/* constants */
import { requiredParams } from '@/components/common/dialog/associatedGoods/constants/skuDimension';
import { EDIT_SKU_INFO_AMOUNT } from '@/constants/exportAmountLimit';
import { modifySkuInfoColumnsFn } from '@/pages/commodity/modules/constants/skuInfoModule';
/* utils */
import { performDifferentTypeMethodsFn } from '@/pages/commodity/modules/utils';
import { getSkuVolumnByCalculate, getCanOpeState } from '@/utils/getUtils';
import { isResponseSuccessState } from '@/utils/bizUtils';
import { getFooterFieldsService } from '@/api/commodity/common';
export default {
  mixins: [skuDimensionMixins],
  components: {
    GeneralTable,
    FooterFields,
    AssociatedGoodsModal,
    SelectUnitDialog,
    OriginalPlaceDialog,
    SeniorLinkedDialog,
    LaunchReasonInput
  },
  data () {
    return {
      canOpeState: true, // 页面可操作状态
      footerFields: {}, // 表尾字段
      launchReason: '', // 发起原因
      seniorAssociated: {
        visible: false,
        isSenior: false, // 是否是高级关联，true是，false为普通关联
        columns: [
          {
            label: 'SKU编码',
            prop: 'skuNo',
            type: 'textarea'
          }
        ],
        dataSource: [{ skuNo: '' }]
      },
      originalPlaceVisible: false,
      associatedGoods: {
        requestApi: {
          url: ['/sysback/update/sku/package/getSkuList'],
          type: 'post'
        },
        requestParams: requiredParams.requestParams,
        distinctParams: requiredParams.distinctParams,
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: '商品名称',
            key: 'productName',
            width: 180
          },
          {
            title: 'SPU编码',
            key: 'spuNo',
            width: 210
          },
          {
            title: 'SKU编码',
            key: 'skuNo',
            width: 210
          },
          {
            title: '商品分类',
            key: 'categoryPath',
            width: 210
          },
          {
            title: '规格参数',
            key: 'specDetailStr',
            width: 180
          },
          {
            title: '品牌',
            key: 'brandName',
            width: 150
          },
          {
            title: '操作',
            slot: 'action',
            align: 'center',
            fixed: 'right',
            minWidth: 100
          }
        ]
      },
      loading: {
        table: false, // 表格加载loading
        submit: false, // 提交按钮loading
        export: false // 导出按钮loading
      },
      pageState: {
        menu: false, // 菜单
        view: false, // 查看
        edit: false, // 修改
        single_sku: false, // SKU管理
        single_spu: false // SPU管理
      },
      storageCurrentRowData: {}, // 备份当前操作表格行的数据
      tableColumns: [], // sku表格列表字段
      tableData: [],
      mainUnitVisible: false, // 控制主计量单位模态框的开关状态
      unitName: '', // 计量单位
      conformShowBtnConditions: ['未提交', '审核未通过'], // 暂存按钮或提交按钮是否可显示的条件之一
      recordNo: '', // 单据号
      reminded: true, // 提交物流检测是否已校验标识，初始默认true，当返回tips提示时，更改状态为false
      apiSourceList: {
        /* 查询基本信息-- 用单据号查询 */
        queryTableDataFromDocManage: {
          url: '/sysback/product/update/record/queryRecordPackage',
          type: 'post'
        },
        /* 查询基本信息---uuid查询_来自SPU查询 */
        queryTableDataFromSpu: {
          url: '/sysback/update/product/package/queryPackageListFromSpu',
          type: 'post'
        },
        /* 查询基本信息---skuNo查询_来自SKU查询 */
        queryTableDataFromSku: {
          url: '/sysback/update/product/package/queryPackageListFromSku',
          type: 'post'
        },
        /* 单据信息-- 根据recordNo查询 */
        getFooterFieldsByRecordNo: {
          url: '/sysback/product/update/record/getByRecordNo',
          type: 'post'
        },
        /* 单据信息-- 根据productUuid查询 */
        getFooterFieldsByUuid: {
          url: '/sysback/product/update/record/queryRecordExist',
          type: 'post'
        },
        /*  查询单据信息---skuNo查询_来自SKU查询 */
        getFooterFieldsBySkuNo: {
          url: '/sysback/product/update/record/queryRecordExistBySku',
          type: 'post'
        }
      },
      apiObj: {
        // 提交
        commitBasicInfo: {
          url: '/sysback/update/product/package/commitPackage', // 接口地址
          type: 'post' // 接口请求类型
        },
        // 暂存
        savePackage: {
          url: '/sysback/update/product/package/savePackage',
          type: 'post' // 接口请求类型
        },
        // 按商品导出SKU包装
        exportPageToExcelPost: {
          url: '/sysback/update/product/package/exportPageToExcelPost',
          type: 'post'
        }
      }
    };
  },
  watch: {
    '$route.path' (newValue) {
      this.$router.go(0);
    }
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    pageTitle () {
      let title = '修改SKU信息';
      let { menu, view } = this.pageState;
      if (menu) {
        return title;
      } // 从菜单修改sku页面进入
      if (view) {
        // 查看页面
        title = `${title}-表单查看页面`;
        return title;
      }
      title = `${title}-表单修改页面`; // 修改页面
      return title;
    }
  },
  mounted () {
    this.setCanOpeState()
    this.initPageDataFn(); // 获取路由参数
    this.tableColumns = _.cloneDeep(
      modifySkuInfoColumnsFn({
        handleChooseMainUnit: this.handleChooseMainUnit,
        isView: this.pageState.view,
        handleChooseOriginalPlace: this.handleChooseOriginalPlace
      })
    );
    // 刷新页面清除选择的供应商缓存
    window.localStorage.removeItem('selectSupplyList');
  },
  methods: {
    // 设置页面是否可操作状态值
    async setCanOpeState () {
      this.canOpeState = await getCanOpeState(this.$route.name)
    },
    // 获取字段信息
    async getFieldsInfo (recordNo) {
      if (!recordNo) return
      const retData = await getFooterFieldsService({ recordNo }, '.footer_fields_card');
      if (retData) {
        this.launchReason = retData.launchReason;
        this.footerFields = retData;
      }
    },
    /* 获取产地信息方法 */
    getOriginalPlaceFn (data) {
      let { producingAreaName, producingAreaCode } = data;
      let { index } = this.storageCurrentRowData;
      this.tableData[index].producingAreaNameUpdate = producingAreaName;
      this.tableData[index].producingAreaCodeUpdate = producingAreaCode;
    },
    /* 选择产地事件 */
    handleChooseOriginalPlace ({ index }) {
      this.storageCurrentRowData.index = index;
      this.originalPlaceVisible = true;
    },
    /* 初始化页面数据 */
    initPageDataFn () {
      let { recordNo, uuid, skuNo, type } = this.$route.query;
      if (!type && recordNo) {
        // 如果有单据号，但是没有type值，说明是从OA跳过来的查看页面
        type = 'view';
      }
      let pageType = type || 'menu';
      this.pageState[pageType] = true;
      if (!type) {
        return false;
      } // 如果没有type，表明是菜单页面，无需调用下面的逻辑方法
      this.recordNo = recordNo || '';
      let params = {
        recordNo,
        uuid,
        type,
        skuNo,
        apiSourceList: this.apiSourceList,
        commitType: 'package',
        getExistTableDataAction: this.getExistTableDataAction,
        initQueryExistRecordAction: () => {}
      };
      performDifferentTypeMethodsFn(params);
      this.getFieldsInfo(recordNo);
    },
    /* 获取已存在的表格数据方法 - 表单管理页面，SPU和SKU管理页面进入时调用，菜单界面的修改SKU不调用 */
    getExistTableDataAction (data) {
      const { api, params } = data;
      this.loading.table = true;
      // 开始请求列表
      ApiRequest(api.url, api.type, params, true).then((res) => {
        this.loading.table = false;
        if (res.retStatus !== '1') { return false }
        res.retData.forEach((row) => {
          this.ASSOCIATED_GOODS({ row });
        });
        this.initTableDataFn(res.retData);
      }).catch(() => {
        this.loading.table = false;
      });
    },
    /* 组装表格数据的方法 */
    initTableDataFn (dataSource) {
      if (!dataSource || dataSource.length === 0) {
        this.tableData = [];
        return false;
      }
      this.tableData = dataSource.reduce((value, item) => {
        value.push({
          productKey: item.spuNo,
          ...item
        });
        return value;
      }, []);
    },
    /* 表格input输入框执行的方法，在计算体积的时候调用 */
    handleChangeInputNumber (data) {
      let { row, columnName } = data;
      let typeSplit = _.lowerCase(columnName).split(' '); // 转换字符串string以空格分开单词，并转换为小写,并通过split切割成对应的数组
      let type = typeSplit[0]; // 只取第一项，分别对应 single one two three四种情况
      row[`${type}VolumeUpdate`] = getSkuVolumnByCalculate({
        type: { start: type, end: 'Update' },
        row
      });
    },
    /* 删除表格对应行的方法 */
    handleCancelSelect (data) {
      let { row } = data;
      this.tableData = this.tableData.filter(item => row.skuNo !== item.skuNo);
      this.updateColumnsByUpdateTableData(true)
      if (!this.seniorAssociated.isSenior) {
        this.CANCEL_GOODS({ row });
      }
    },
    /* 更改对应表格主计量单位的方法 */
    handleReturnMainUnitName (unitName) {
      let { type, index } = this.storageCurrentRowData;
      this.tableData[index][type] = unitName;
    },
    /* 选择主计量单位的方法 */
    handleChooseMainUnit (data) {
      this.storageCurrentRowData = data;
      this.mainUnitVisible = true;
    },
    /* 高级关联事件 */
    handleSeniorAssociated () {
      const curBtnId = getBtnsId('高级关联');
      sessionStorage.setItem('buttonId', curBtnId);
      this.seniorAssociated.visible = true;
    },
    /* 获取高级关联结果方法 */
    getSeniorResultFn (data) {
      this.seniorAssociated.isSenior = true;
      this.CLEAR_GOODS();
      this.getTableDataAction(data);
    },
    /* 获取关联商品后的表格数据的方法 */
    handleGetTableData () {
      this.seniorAssociated.isSenior = false;
      const selectedSkuList = this.getSkuNoListFn(this.getListFromMapFn());
      if (selectedSkuList.length === 0) {
        this.initTableDataFn();
        return false
      }
      this.getTableDataAction(selectedSkuList);
    },
    /* 获取关联商品后的表格数据的方法 */
    getTableDataAction (data) {
      this.loading.table = true;
      ApiRequest(
        '/sysback/update/product/package/queryPackageListBySku',
        'post',
        data,
        false
      ).then((res) => {
        this.loading.table = false;
        if (res.retStatus !== '1') return
        this.initTableDataFn(res?.retData ?? [])
        this.updateColumnsByUpdateTableData()
      }).catch(() => {
        this.loading.table = false;
      });
    },
    // 获取表格数据后更新表列
    updateColumnsByUpdateTableData (noWarning) {
      const EDIT_LIMITS = 200
      const hasExcceedLimits = this.tableData.length > EDIT_LIMITS
      if (!noWarning && hasExcceedLimits) {
        this.$message.warning(`关联商品数量超过${EDIT_LIMITS}条，请导出到Excel中进行维护`)
      }
      this.tableColumns = _.cloneDeep(modifySkuInfoColumnsFn({
        handleChooseMainUnit: this.handleChooseMainUnit,
        isView: hasExcceedLimits,
        handleChooseOriginalPlace: this.handleChooseOriginalPlace
      }))
      hasExcceedLimits && this.tableColumns.push({
        title: '操作',
        key: 'action',
        fixed: 'right'
      })
    },
    /* 点击关联商品的事件 */
    handleAssociatedGoods () {
      let curBtnId = getBtnsId('关联商品');
      sessionStorage.setItem('buttonId', curBtnId);
      this.CHANGE_MODAL_SWITCH(true);
      /* this.$nextTick(() => {
        this.$refs.link.getDataListAction();
      }); */
    },
    /* 暂存的方法 */
    handleSaveData () {
      if (this.tableData.length > EDIT_SKU_INFO_AMOUNT) {
        return this.$message.warning(
          `当前单据提交的行数不能超过${EDIT_SKU_INFO_AMOUNT}`
        );
      }
      let data = {
        recordNo: this.recordNo,
        inputList: this.tableData,
        launchReason: this.launchReason // 发起原因
      };
      let { url, type } = this.apiObj.savePackage;
      this.loading.submit = true;
      return new Promise((resolve, reject) => {
        ApiRequest(url, type, data, false)
          .then((res) => {
            this.loading.submit = false;
            if (res.retStatus !== '1') {
              return false;
            }
            this.$message.success('暂存成功');
            this.recordNo = res.retData.recordNo;
            resolve(true);
          })
          .catch((err) => {
            this.loading.submit = false;
            reject(err);
          });
      });
    },
    // 提交包装信息
    handleSubmit () {
      this.$confirm(
        '确认提交信息吗？',
        { title: '提示', type: 'warning' }
      ).then(() => {
        this.submitSkuInfo();
      }).catch(() => {});
    },
    // 提交请求
    async requestToSubmit () {
      const { url, type } = this.apiObj.commitBasicInfo;
      try {
        this.loading.submit = true;
        const res = await ApiRequest(
          `${url}?recordNo=${this.recordNo}&reminded=${this.reminded}`,
          type,
          this.tableData
        );
        this.loading.submit = false;
        return res;
      } catch (err) {
        this.loading.submit = false;
      }
    },
    // 提交包装信息
    async submitSkuInfo () {
      const hasSaved = await this.handleSaveData();
      if (!hasSaved) { return false; }
      const res = await this.requestToSubmit();
      if (isResponseSuccessState(res.retStatus)) {
        if (res.retData?.tips) {
          this.confirmTipsByLogisticsMeasured(res.retData.tips);
        } else {
          this.$message.success('提交成功');
          this.$router.push({ name: 'chageFromManageList' });
        }
      }
    },
    // 确认弹框 物流是否已测量
    confirmTipsByLogisticsMeasured (tips) {
      if (tips) {
        this.$confirm(
          '存在物流已维护过包装参数的商品，请确认是否再次修改？',
          {
            title: '提示',
            type: 'warning',
            cancelButtonText: '查看详情',
            confirmButtonText: '仍要提交'
          }
        ).then(() => {
          this.reminded = false;
          this.submitSkuInfo();
        }).catch(() => {});
      }
    },
    /* 导出数据 */
    handleExportData () {
      let { url, type } = this.apiObj.exportPageToExcelPost;
      this.loading.export = true;
      ApiRequestExportTable(url, type, this.tableData, false)
        .then((res) => {
          this.loading.export = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '修改SKU信息.xlsx';
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.loading.export = false;
          this.$message.error('导出失败');
        });
    },
    /* 上传格式验证失败 */
    handleUploadFormatError (file, fileList) {
      this.loading.table = false;
      this.$message.error('格式错误');
    },
    /* 上传之前 */
    handleBeforeUpload () {
      this.loading.table = true;
      this.tableData = [];
    },
    /* 上传成功 */
    handleUploadSuccess (res, file, fileList) {
      this.loading.table = false;
      if (res.retStatus !== '1') {
        return this.$message.error(res.retMessage);
      }
      // 如果上传成功,并且接口返回成功,对表格进行赋值操作.
      this.tableData = res.retData;
      this.tableData.forEach((value) => {
        value.productKey = value.spuNo;
        value.singleVolumeUpdate = getSkuVolumnByCalculate({
          type: { start: 'single', end: 'Update' },
          row: value
        });
        value.oneVolumeUpdate = getSkuVolumnByCalculate({
          type: { start: 'one', end: 'Update' },
          row: value
        });
        value.twoVolumeUpdate = getSkuVolumnByCalculate({
          type: { start: 'two', end: 'Update' },
          row: value
        });
        value.threeVolumeUpdate = getSkuVolumnByCalculate({
          type: { start: 'three', end: 'Update' },
          row: value
        });
      });
      this.updateColumnsByUpdateTableData()
    },
    /* 上传失败 */
    handleUploadError () {
      this.loading.table = false;
      this.$message.error('上传失败');
    },
    // 返回上一页
    handleGoBack () {
      let routerName = 'chageFromManageList';
      if (this.pageState.single_spu) {
        routerName = 'SPUManageList';
      } else if (this.pageState.single_sku) {
        routerName = 'SKUManageList';
      }
      this.$router.push({ name: routerName })
    }
  }
};
</script>
<style lang="less" scoped>
/deep/ .ivu-upload {
  margin: 0 5px;
}
</style>
